package servlet;

import dao.UserDAO;
import model.User;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.util.List;

@WebServlet("/UserServlet")
public class UserServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String action = request.getParameter("action");

        if ("add".equals(action)) {
            String username = request.getParameter("username");
            String password = request.getParameter("password");

            User user = new User(0, username, password);
            UserDAO.addUser(user);
            response.sendRedirect("UserServlet");  // 重定向到 GET 请求

        } else if ("update".equals(action)) {
            int id = Integer.parseInt(request.getParameter("id"));
            String username = request.getParameter("username");
            String password = request.getParameter("password");

            User user = new User(id, username, password);
            UserDAO.updateUser(user);
            response.sendRedirect("UserServlet");  // 重定向到 GET 请求

        } else if ("delete".equals(action)) {
            int id = Integer.parseInt(request.getParameter("id"));
            UserDAO.deleteUser(id);
            response.sendRedirect("UserServlet");  // 重定向到 GET 请求
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<User> users = UserDAO.findUsers();
        request.setAttribute("users", users);
        request.getRequestDispatcher("users.jsp").forward(request, response);
    }
}